package com.we.web.servlet;

import com.we.entity.ResultInfo;
import com.we.entity.User;
import com.we.service.UserService;
import com.we.service.impl.UserServiceImpl;
import com.we.util.Base64Utils;
import com.we.util.JsonUtils;
import com.we.util.Md5Utils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

/**
 * 用户请求处理servlet
 */
@WebServlet("/user")
public class UserServlet extends BaseServlet {

    private UserService service = new UserServiceImpl();
    private ResultInfo info = new ResultInfo();

    //检查用户名方法
    public void checkUserName(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userName = req.getParameter("userName");
        User user = service.findUserByName(userName);
        if (user != null) {
            info.setFlag(false);
            info.setErrorMsg("用户名重复，请检查");
        } else {
            info.setFlag(true);
        }
        JsonUtils.writeValue(info, resp);
    }

    //检查邮箱方法
    public void checkEmail(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String email = req.getParameter("email");
        User user = service.findUserByEmail(email);
        if (user != null) {
            info.setFlag(false);
            info.setErrorMsg("邮箱重复，请检查");
        } else {
            info.setFlag(true);
        }
        JsonUtils.writeValue(info, resp);
    }

    //注册方法
    public void regist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //校验验证码
        String checkCode = req.getParameter("yzm");
        String code = (String) req.getSession().getAttribute("CHECKCODE_SERVER");
        //获取后从session中清除
        req.getSession().removeAttribute("CHECKCODE_SERVER");
        if (checkCode == null || !checkCode.equalsIgnoreCase(code)) {
            info.setFlag(false);
            info.setErrorMsg("验证码错误");
            JsonUtils.writeValue(info, resp);
            return;
        }

        User user = new User();
        try {
            BeanUtils.populate(user, req.getParameterMap());
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

        user.setPassword(Md5Utils.md5(req.getParameter("password")));
        boolean flag = service.addUser(user);

        if (!flag) {
            info.setFlag(false);
            info.setErrorMsg("注册失败");
            JsonUtils.writeValue(info, resp);
        } else {
            info.setFlag(true);
        }
        JsonUtils.writeValue(info, resp);
    }

    //激活方法
    public void active(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String code = request.getParameter("code");
        if (code != null) {
            boolean flag = service.active(code);
            if (flag) {
                response.getWriter().write("<script>alert(激活成功)</script>");
                ;
                response.sendRedirect(request.getContextPath() + "/login.html");
            } else {
                String msg = "<h1>激活失败，请联系管理员!</h1>";
                response.getWriter().write(msg);
            }
        }
    }

    //登录方法
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //校验验证码
        String checkCode = request.getParameter("yzm");
        String code = (String) request.getSession().getAttribute("CHECKCODE_SERVER");
        //获取后从session中清除
        request.getSession().removeAttribute("CHECKCODE_SERVER");
        if (checkCode == null || !checkCode.equalsIgnoreCase(code)) {
            info.setFlag(false);
            info.setErrorMsg("验证码错误");
            JsonUtils.writeValue(info, response);
            return;
        }

        User user = new User();
        try {
            BeanUtils.populate(user, request.getParameterMap());
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

        user.setPassword(Md5Utils.md5(user.getPassword()));

        User u = service.login(user);
        if (u == null) {
            info.setFlag(false);
            info.setErrorMsg("用户名或密码错误");
        }
        if (u != null && !"Y".equals(u.getStatus())) {
            info.setFlag(false);
            info.setErrorMsg("您尚未激活，请先激活");
        }
        if (u != null && "Y".equals(u.getStatus())) {
            info.setFlag(true);
            request.getSession().setAttribute("user", u);
            String auto = request.getParameter("auto");
            if (auto == null) {
                Cookie cookie = new Cookie("autoUser", "");
                cookie.setPath("/");
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            } else {
                String content = u.getUserName() + ":" + Base64Utils.encode(u.getPassword());
                Cookie cookie = new Cookie("autoUser", content);
                cookie.setPath("/");
                cookie.setMaxAge(60 * 60 * 24 * 14);
                response.addCookie(cookie);
            }
        }

        JsonUtils.writeValue(info, response);
    }

    //退出方法
    public void exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("autoUser", null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath() + "/login.html");
    }

    //修改密码方法
    public void updatePwd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            info.setFlag(false);
            info.setErrorMsg("当前用户未登录，请先登录");
            JsonUtils.writeValue(info, response);
            return;
        }

        String password = request.getParameter("password");
        if (!user.getPassword().equals(Md5Utils.md5(password)) || password == null || password.equals("")) {
            info.setFlag(false);
            info.setErrorMsg("原密码错误");
            JsonUtils.writeValue(info, response);
            return;
        }

        String newpassword = request.getParameter("newpassword");
        boolean flag = service.updatePwd(Md5Utils.md5(newpassword), user.getUserName());
        if (!flag) {
            info.setFlag(false);
            info.setErrorMsg("修改密码失败");
        } else {
            info.setFlag(true);
            Cookie cookie = new Cookie("autoUser", null);
            cookie.setPath("/");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
        JsonUtils.writeValue(info, response);
    }

    //找回密码方法
    public void forgetPws(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName=request.getParameter("userName");
        String email=request.getParameter("email");
        String password=request.getParameter("password");

        if(StringUtils.isBlank(userName) || StringUtils.isBlank(email) || StringUtils.isBlank(password)){
            info.setFlag(false);
            info.setErrorMsg("所填信息不能为空");
        }

        int count = service.forgetPws(Md5Utils.md5(password),userName,email);
        if (count<=0) {
            info.setFlag(false);
            info.setErrorMsg("找回密码失败，请检查输入内容");
        } else {
            info.setFlag(true);
            Cookie cookie = new Cookie("autoUser", null);
            cookie.setPath("/");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
        JsonUtils.writeValue(info, response);
    }

    //查询用户名(昵称)
    public void findUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");
        JsonUtils.writeValue(user,response);
    }

    //更改用户信息方法
    public void updateUserById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            info.setFlag(false);
            info.setErrorMsg("当前用户未登录，请先登录");
            JsonUtils.writeValue(info, response);
            return;
        }

        User user1=new User();
        try {
            BeanUtils.populate(user1,request.getParameterMap());
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

        int flag=service.updateUserById(user1);
        if(flag>0){
            info.setFlag(true);
            request.getSession().removeAttribute("user");
            request.getSession().setAttribute("user",user1);
        }else{
            info.setFlag(false);
            info.setErrorMsg("修改信息失败");
        }
        JsonUtils.writeValue(info,response);
    }
}
